package com.netty.rpc.loadbalance;

import com.netty.rpc.registar.RpcClientEntity;
import com.netty.rpc.common.entity.NettyClient;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;


public class RandomLoadBalanceExecutor extends AbstractLoadBalanceExecutor {

    @Override
    protected RpcClientEntity loadBalance(RpcClientEntity rpcClientEntity, String interfaceName, List<NettyClient> candidates) {
        if (candidates == null || candidates.size() == 0) {
            return null;
        }
        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        int index = threadLocalRandom.nextInt(candidates.size());
        NettyClient nettyClient = candidates.get(index);
        RpcClientEntity entity = new RpcClientEntity();
        BeanUtils.copyProperties(nettyClient, entity);
        entity.setIsSyn(rpcClientEntity.isSyn());
        entity.setRpcClz(rpcClientEntity.getRpcClz());
        return entity;
    }
}
